﻿using UnityEngine;

namespace Assets.Scripts
{
    /// <summary>
    /// 乒乓球.
    /// 现在只是测试
    /// </summary>
    public class Ball : MonoBehaviour
    {
        private Rigidbody2D _rigidbody2D;

        private void Awake()
        {
            InitWidget();
        }

        private void Start()
        {
            Init();
        }

        /// <summary>
        /// 获取组件函数.
        /// </summary>
        private void InitWidget()
        {
            _rigidbody2D = GetComponent<Rigidbody2D>();
        }

        /// <summary>
        /// 初始化函数.
        /// </summary>
        private void Init()
        {
            _rigidbody2D.velocity = new Vector2(-1 * DataManager.Instance.BallMoveSpeed, 0);
        }

        /// <summary>
        /// 碰撞检测.
        /// </summary>
        /// <param name="other">碰撞到的碰撞体</param>
        private void OnTriggerEnter2D(Collider2D other)
        {
            //检测是否碰到了球拍.
            if (other.CompareTag("Racket"))
            {
                Debug.Log("碰到了球拍:" + other.gameObject.name);
                //反向.
                _rigidbody2D.velocity =
                    new Vector2(-_rigidbody2D.velocity.x, other.GetComponent<Rigidbody2D>().velocity.y);
                _rigidbody2D.velocity += (_rigidbody2D.velocity.x > 0 ? 1 : -1) *
                                         new Vector2(DataManager.Instance.BallSpeedDelta, 0);
                Debug.Log("球的速度为:" + _rigidbody2D.velocity);
            }
            //检测是否碰到了墙.
            if (other.CompareTag("Wall"))
            {
                //反弹.
                _rigidbody2D.velocity =
                    new Vector2(_rigidbody2D.velocity.x, -_rigidbody2D.velocity.y);
            }
        }
    }
}
